/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gestioninscription;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.*;
import sql.GestionBdd;
/**
 *
 * @author Utilisateur
 */
public class FenSession extends javax.swing.JFrame {
    
    Connection conn;
    Statement stmt;
    ResultSet rs;
    /**
     * Creates new form FenSession
     */
    public FenSession() {
        initComponents();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("GESTION DES SESSIONS");

        jTable1.setModel(new ModeleJTableListeSession2());
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened


	String pilote = "org.gjt.mm.mysql.Driver";
	String url = "jdbc:mysql://127.0.0.1/formarmor";
        
        try
	{
            Class.forName(pilote);           			            
            conn = DriverManager.getConnection(url,"root","");
            stmt = conn.createStatement();
            stmt = GestionBdd.connexionBdd(GestionBdd.TYPE_MYSQL, "formarmor","localhost", "root","");

            renseigne();

            }
            catch (SQLException se)
            {
                System.out.println("Erreur SQL1 : " + se.getMessage());
            }
            catch(ClassNotFoundException ce)
            {
               System.out.println("Erreur classe : " + ce.getMessage());
            }
    }//GEN-LAST:event_formWindowOpened

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        Document document = new Document();
        float[] columnWidths = {3f, 10f, 6f};

        try {
            PdfWriter.getInstance(document,
                new FileOutputStream("./Emargement.pdf"));

            document.open();
            
            Image image = Image.getInstance("banniere.png");
            image.scalePercent(90f);
            document.add(image);
            
            document.add(new Paragraph(" "));
            
            PdfPTable table = new PdfPTable(3);
            table.setWidths(columnWidths);
            
            String date =jTable1.getValueAt(jTable1.getSelectedRow(), 3).toString();
            String[] tabDate = date.split("-");
            String dateFinal = tabDate[2] + "/" + tabDate[1] + "/" + tabDate[0];
            PdfPCell cellTitre = new PdfPCell(new Paragraph("Liste d'émargement de la session '" + jTable1.getValueAt(jTable1.getSelectedRow(), 1).toString() + " " + jTable1.getValueAt(jTable1.getSelectedRow(), 2).toString() + "', le " + dateFinal));
            cellTitre.setColspan(3);
            cellTitre.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellTitre);
            
            PdfPCell cellCol1 = new PdfPCell(new Paragraph("Numéro"));
            cellCol1.setHorizontalAlignment(Element.ALIGN_CENTER);
            PdfPCell cellCol2 = new PdfPCell(new Paragraph("Nom - Prénom"));
            cellCol2.setHorizontalAlignment(Element.ALIGN_CENTER);
            PdfPCell cellCol3 = new PdfPCell(new Paragraph("Signature"));
            cellCol3.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellCol1);
            table.addCell(cellCol2);
            table.addCell(cellCol3);
            
            rs = stmt.executeQuery("SELECT nom from client, inscription WHERE inscription.matricule = client.matricule AND num_session =" + jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString());
            int compteur = 1;
            while(rs.next())
            {
                table.addCell(""+compteur+"");
                table.addCell(new Paragraph(rs.getObject(1).toString()));
                table.addCell(" ");
                compteur++;
                
            }
            rs.close();
            document.add(table);
            document.close();
            if ((new File("./Emargement.pdf")).exists()) {
 
			Process p = Runtime
			   .getRuntime()
			   .exec("rundll32 url.dll,FileProtocolHandler Emargement.pdf");
			p.waitFor();
 
		} else {
 
			System.out.println("File is not exists");
 
		}
            

        } catch (DocumentException de) {
            de.printStackTrace();
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (SQLException sqle) {
            sqle.printStackTrace();
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
    }//GEN-LAST:event_jTable1MouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FenSession.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FenSession.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FenSession.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FenSession.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new FenSession().setVisible(true);
            }
        });
    }
    
    private void renseigne()
    {
        try
        {
            rs = stmt.executeQuery("select numero, libelleform, niveauform, datedebut, nb_places, nb_inscrits from session_form where datedebut > now() order by datedebut");
            int ligne = 0, col;

            for(int i=0;i<jTable1.getRowCount();i++)
            {
                for (col=0;col<jTable1.getColumnCount();col++)
                {
                        jTable1.setValueAt(null,i,col);
                }
            }
            while(rs.next())
            {
                for(col=0; col < jTable1.getColumnCount(); col++)
                {   
                    jTable1.setValueAt(rs.getObject(col + 1), ligne, col);
                }              
                ligne++;
            }
            rs.close();
        }
        catch (SQLException SQLE)
        {
            System.out.println("Erreur SQL: " + SQLE.getMessage());
        }
        
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
